package com.imc.platform.base.notice.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.imc.core.utils.ClearTempImg;
import com.imc.core.utils.MenuUtils;
import com.imc.core.utils.MysqlUtil;
import com.imc.platform.base.category.pojo.Category;
import com.imc.platform.base.notice.pojo.Notice;
import com.imc.platform.base.notice.pojo.NoticeAttach;
import com.imc.platform.base.notice.service.INoticeService;
import com.imc.platform.base.role.service.IRoleService;
import com.imc.platform.base.user.pojo.User;
import com.twp.common.component.process.exception.combo.IComboExecptionForTFunc;
import com.twp.common.tuple.ResultDTO;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.session.Session;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 类描述: 公告管理controller
 * 开发者:SJC
 * 创建时间:2018-8-17 16:37:33
 */
@Slf4j
@Controller
public class NoticeController {

    public static final String imgUrl = "/images/notice/";

    @Autowired
    INoticeService iNoticeService;

    @Autowired
    MysqlUtil mysqlUtil;

    @Autowired
    MenuUtils menuUtils;
    @Autowired
    IComboExecptionForTFunc iComboExecptionForTFunc;
    @Autowired
    ClearTempImg clearTempImg;

    @Autowired
    private IRoleService roleService;


    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    public static class ReqTuple{
        List<String> memberList;
        String noticeId;
        String contentDetail;
        String title;
        String type;
        String authorId;
    }

    /*
     *  sjc 2018-8-17 10:01:50
     *  方法描述：公告页面跳转
     */
    @RequestMapping("/index/noticeManage")
    public String noticeManage(String menuId,Model model,HttpServletRequest request){
        model.addAttribute("menu", menuUtils.getMenuByRoleId(request,menuId));
        model.addAttribute("menuId",menuId);
        return "base/notice/noticeManage";
    }

    /**
     * 方法描述:公告查询
     * SJC 2018-8-22 10:24:41
     */
    @RequestMapping("/notice/queryNotice")
    @ResponseBody
    public ResultDTO queryNotice(Pageable pageable) throws Exception {
        PageInfo<Notice> noticeList = iNoticeService.queryNotice(pageable.getPageNumber(), pageable.getPageSize());
        for(Notice c : noticeList.getList()){
            c.setPageNumber(pageable.getPageNumber());
            c.setPageSize(pageable.getPageSize());
        }
        JSONObject map = new JSONObject();
        map.put("total", noticeList.getTotal());
        map.put("rows", noticeList.getList());
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;
    }

    /**
     * 方法描述:跳转到新增页面
     * SJC 2018-8-19 19:04:51
     */
    @GetMapping("/notice/openAddNotice")
    public String toaddNotice(Model model,@RequestParam String type,@RequestParam String parentId) throws Exception {
//        List<Category> categoryList = iNoticeService.queryCategory();
//        model.addAttribute("categoryList",categoryList);
        model.addAttribute("type",type);
        model.addAttribute("backUrl",menuUtils.getMealUrlByParentId(parentId));
        return "base/notice/addNoticeTinymce";
    }

    /**
    *类描述：规章制度
    *开发者：QY
    *创建时间：2018/12/13 8:45
    **/
    @GetMapping("/index/showRegulatoryPage")
    public String showRegulatoryPage(Model model){
        String type="35";
        Notice nt = iNoticeService.queryNoticeById("4");
        if(!"".equals(nt.getContent())){
            nt.setContent(nt.getContent());
        }
        nt.setSendIdList(iNoticeService.querySendMember("4",nt.getAuthorId()));
        model.addAttribute("notice", nt);
        List<NoticeAttach> naList = iNoticeService.queryNoticeAttachList("4");
        model.addAttribute("naList", naList);
        model.addAttribute("backUrl",menuUtils.getMealUrlByParentId("1"));
        if(type.contains("?")){
            type = type.split("\\?")[0];
        }
        model.addAttribute("type", type);

        if("1".equals(type)){
            return "base/introducemanage/updateIntroduceTinymce";
        }else{
            return "base/notice/updateNoticeTinymce";
        }
    }

    /**
     * 方法描述:新增公告
     * SJC 2018-8-19 19:04:51
     */
    @RequestMapping("/notice/addNoticeTitle")
    @ResponseBody
    public ResultDTO addNoticeTitle(String noticeTitle,String noticeType, HttpServletRequest request){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    User user=(User) request.getSession().getAttribute("currentUser");
                    Notice notice=Notice.builder()
                            .title(noticeTitle)
                            .noticeType(noticeType)
                            .authorId(String.valueOf(user.getId()))
                            .authorName(user.getLoginName())
                            .createTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
                            .orgId(user.getOrgId())
                            .build();
                    iNoticeService.addNoticeTitle(notice);
                    t.setData(notice.getId());
                    t.setMessage("创建成功");

                },
                (e,t)->{
                    t.setMessage("创建失败");
                    t.setIsSuccess(false);
                    t.setCode("201");
                    t.setData(e.getMessage());
                });
    }


    /**
     * 方法描述:新增内容模块
     * SJC 2018-8-27 16:04:49
     */
   /* @RequestMapping("/notice/addNoticeDetail")
    @ResponseBody
    public ResultDTO addNoticeDetail(String ntId, String contCount, String contentType) throws Exception {

        System.out.println("addNoticeDetail start");

        JSONObject map = new JSONObject();
        //新增模块
        NoticeDetail nd = new NoticeDetail();
        nd.setParentId(ntId);
        nd.setContent("无内容！");
        //模块排序
        nd.setSn(contCount);
        //内容类型 1：文字 2：图片 3：视频
        nd.setContentType(contentType);
        int noticeDetailId = iNoticeService.addNoticeDetail(nd);
        if (noticeDetailId != 0) {
            map.put("ndId", noticeDetailId);
            System.out.println("======addNoticeDetail====noticeDetailId:" + noticeDetailId);
            map.put("reCode", "4001");
        } else {
            map.put("reCode", "4002");
        }
        ResultDTO obj = ResultDTO.builder().data(map).build();
        System.out.println("obj" + obj);
        return obj;

    }
*/

   @GetMapping("/notice/querySelectCatList")
   @ResponseBody
   public ResultDTO querySelectCatList(){
       return iComboExecptionForTFunc.executeFlow(
               ResultDTO.builder().build(),
               t->{
                   t.setData(iNoticeService.querySelectCatList());
                   t.setMessage("查询成功");
               },
               (e,t)->{
                   t.setMessage("查询失败");
                   t.setIsSuccess(false);
                   t.setCode("201");
                   t.setData(e.getMessage());
               });
   }

    //绝对路径
    public String path(HttpServletRequest request){
        //开发用：
//        String indeStr = "http://" + request.getServerName() // 服务器地址
//                + ":" + request.getServerPort() // 端口号
//                + request.getContextPath(); // 项目名称
//        //现网：
//        /*String indeStr = "https://" + request.getServerName() // 服务器地址
//                + request.getContextPath(); // 项目名称*/
        return accessPath+imgUrl;
    }

    @Value("${img.location}")
    String location;

    @Value("${img.accessPath}")
    String accessPath;

    //相对路径
    public String savePath(HttpServletRequest request){
        //String savePath = request.getSession().getServletContext().getRealPath(imgUrl);
        return location + imgUrl;
    }

    /**
     * 方法描述:新增内容块和图片上传
     * SJC 2018-8-26 17:28:56
     */
    @RequestMapping("/notice/addNoticeAttach")
    @ResponseBody
    public ResultDTO addNoticeAttach(@RequestParam("file") MultipartFile file, String ntId, HttpServletRequest request) throws Exception {
        JSONObject map = new JSONObject();
        //图片模块上传多图片时候，只新增附件表。
        if (null != ntId && !"".equals(ntId)) {
            String realPath=path(request);
            String savePath =savePath(request);
            String fileName = upImg(savePath, file);
            if (null != fileName && !"".equals(fileName)) {
                map.put("reCode", "4001");
                NoticeAttach na = new NoticeAttach();
                String naId = mysqlUtil.getMaxId("t_notice_attach");
                na.setId(Integer.parseInt(naId));
                na.setNoticeId(ntId);
                //图片名称
                na.setAttachmentName(fileName);
                na.setAttachmentType("1");
                //图片地址
                na.setAttachmentUrl(realPath + fileName);
                na.setState("1");
                int count = iNoticeService.addNoticeAttach(na);
                if (count == 0) {
                    //附件新增失败
                    map.put("reCode", "4004");
                } else {
                    map.put("reCode", "4001");
                    map.put("naId", naId);
                    map.put("imgName", fileName);
                    map.put("imgUrl", realPath + fileName);
                }
            } else {
                //图片上传失败
                map.put("reCode", "4002");
            }

        }
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;
    }


    /**
     * 方法描述:图片上传 返回图片路径
     * SJC 2018-8-26 16:03:21
     */
    private String upImg(String savePath, MultipartFile file) {

        String relFn = null;
        try {
            if (null != file) {
                String filename = URLEncoder.encode(file.getOriginalFilename(), "utf-8");
                File filepath = new File(savePath, filename);
                //判断路径是否存在，如果不存在就创建一个
                if (!filepath.getParentFile().exists()) {
                    filepath.getParentFile().mkdirs();
                }
                InputStream inputStream = file.getInputStream();
                FileOutputStream fileOutputStream = null;
                String fnName = makeFileName(filename);
                relFn = fnName;
                byte[] data = new byte[1024];
                int len = 0;
                fileOutputStream = new FileOutputStream(savePath + fnName);
                while ((len = inputStream.read(data)) != -1) {
                    fileOutputStream.write(data, 0, len);
                }
                fileOutputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return relFn;
    }

    private static String makeFileName(String filename) { //2.jpg
        //为防止文件覆盖的现象发生，要为上传文件产生一个唯一的文件名
        String extname = filename.substring(filename.lastIndexOf("."), filename.length());
        return UUID.randomUUID().toString() + extname;
    }


    /**
     * 方法描述:查询详情
     * SJC 2018-8-27 16:14:31
     */
    @GetMapping("/notice/showNoticeInfo")
    public String showNoticeInfo(@RequestParam String ntId, Model model) throws Exception {
        Notice nt = iNoticeService.queryNoticeById(ntId);
        if(!"".equals(nt.getContent())){
            nt.setContent(nt.getContent());
        }
        model.addAttribute("notice", nt);
        List<NoticeAttach> naList = iNoticeService.queryNoticeAttachList(ntId);
        model.addAttribute("naList", naList);
        return "base/notice/noticeInfo";

    }


    /**
     * 方法描述:详情查询，用于删除
     * SJC 2018-8-27 16:14:31
     */
    @GetMapping("/notice/toUpdateNotice")
    public String toUpdateNotice(@RequestParam String ntId, Model model) throws Exception {
        Notice nt = iNoticeService.queryNoticeById(ntId);
        if(!"".equals(nt.getContent())){
            nt.setContent(nt.getContent());
        }
        model.addAttribute("notice", nt);
        List<NoticeAttach> naList = iNoticeService.queryNoticeAttachList(ntId);
        model.addAttribute("naList", naList);
        return "base/notice/updateNotice";

    }


    /**
     * 方法描述:删除详细模块
     * SJC 2018-8-19 19:04:51
     */
    @RequestMapping("/notice/delNoticeAttach")
    @ResponseBody
    public ResultDTO delNoticeAttach(@RequestParam String ntId,@RequestParam String imgName) throws Exception {

        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    clearTempImg.clearImgs(imgName);
                    log.info("delNoticeDetail start");
                    int count = iNoticeService.delNoticeAttach(ntId, imgName);
                    log.info("NoticeController id:" + count);
                    JSONObject map = new JSONObject();
                    map.put("count", count);
                    t.setData(map);
                },
                (e,t)->{
                    t.setIsSuccess(false);
                    t.setMessage("删除详细模块失败");
                }
        );
    }

    /**
     * 方法描述:根据id删除公告
     * SJC 2018-9-4 21:52:41
     */
    @RequestMapping(value = "/notice/delNotice", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO delRole(@RequestParam String id) {
        return ResultDTO.builder()
                .data(iNoticeService.delNotice(id))
                .build();
    }


/********************************以下富文本框方法********************************************/


    /**
     * 方法描述:新增公告详细表，获取详细表Id，图片上传，新增公告附件表
     * SJC 2018-8-26 17:28:56
     */
    @RequestMapping("/notice/addNoticeAttachTiny")
    @ResponseBody
    public ResultDTO addNoticeAttachTiny(@RequestParam("file") MultipartFile file, String ntId, HttpServletRequest request) throws Exception {
        JSONObject map = new JSONObject();
        //图片模块上传多图片时候，只新增附件表。

        //新增模块
        if (ntId != null && ntId != "") {
            map.put("ntId", ntId);
            map.put("reCode", "4001");
            String realPath=path(request);
            String savePath = savePath(request);
            String fileName = upImg(savePath, file);
            if (null != fileName && !"".equals(fileName)) {
                map.put("reCode", "4001");
                NoticeAttach na = new NoticeAttach();
                String naId = mysqlUtil.getMaxId("t_notice_attach");
                na.setId(Integer.parseInt(naId));
                na.setNoticeId(ntId);
                //图片名称
                na.setAttachmentName(fileName);
                na.setAttachmentType("1");
                //图片地址
                na.setAttachmentUrl(realPath + fileName);
                na.setState("1");
                int count = iNoticeService.addNoticeAttach(na);
                if (count == 0) {
                    //附件新增失败
                    map.put("reCode", "4004");
                } else {
                    map.put("reCode", "4001");
                    map.put("naId", naId);
                    map.put("imgName", fileName);
                    map.put("imgUrl", realPath + fileName);
                }
            } else {
                //图片上传失败
                map.put("reCode", "4002");
            }

        }
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;
    }


    /**
     * 方法描述:把富文本框内容填充到公告内容表里
     * SJC 2018-8-26 17:28:56
     */
    @RequestMapping("/notice/updateNoticeDetailTiny")
    @ResponseBody
    public ResultDTO updateNoticeDetailTiny(@RequestBody ReqTuple reqTuple,HttpServletRequest request){
        HttpSession session = request.getSession();
        User user=(User) session.getAttribute("currentUser");
        JSONObject map = new JSONObject();
        int count = iNoticeService.updateNoticeContent(reqTuple.getNoticeId(),reqTuple.getContentDetail(),reqTuple.getMemberList(),String.valueOf(user.getId()));
        if (count != 0) {
            map.put("reCode", "4001");
        } else {
            map.put("reCode", "4002");
        }
        ResultDTO obj = ResultDTO.builder().data(map).build();
        return obj;

    }

    /**
     * 方法描述:详情查询 跳到编辑
     * SJC 2018-8-27 16:14:31
     */
    @GetMapping("/notice/toUpdateNoticeTiny")
    public String toUpdateNoticeTiny(@RequestParam String ntId, Model model,@RequestParam String type,@RequestParam String parentId){
        Notice nt = iNoticeService.queryNoticeById(ntId);
        if(!"".equals(nt.getContent())){
            nt.setContent(nt.getContent());
        }
        nt.setSendIdList(iNoticeService.querySendMember(ntId,nt.getAuthorId()));
        model.addAttribute("notice", nt);
        List<NoticeAttach> naList = iNoticeService.queryNoticeAttachList(ntId);
        model.addAttribute("naList", naList);
        model.addAttribute("backUrl",menuUtils.getMealUrlByParentId(parentId));

        if(type.contains("?")){
            type = type.split("\\?")[0];
        }
        model.addAttribute("type", type);

        if("1".equals(type)){
            return "base/introducemanage/updateIntroduceTinymce";
        }else{
            return "base/notice/updateNoticeTinymce";
        }


    }


    /**
     * 方法描述:修改公告信息
     * SJC 2018-8-27 16:14:31
     */
    @RequestMapping(value = "/notice/updateNoticeTiny", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO updateNoticeTiny(@RequestBody ReqTuple reqTuple,HttpServletRequest request){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    User user=(User) request.getSession().getAttribute("currentUser");
                    if (reqTuple.getType().equals("10")){
                        reqTuple.contentDetail = reqTuple.getContentDetail().replaceAll("<[.[^<]]*>", "");
                    }
                    iNoticeService.updateNotice(Notice.builder()
                            .id(Integer.parseInt(reqTuple.getNoticeId()))
                            .title(reqTuple.getTitle())
                            .noticeType(reqTuple.getType())
                            .content(reqTuple.getContentDetail())
                            .sendIdList(reqTuple.getMemberList())
                            .authorId(String.valueOf(user.getId()))
                            .authorName(user.getLoginName())
                            .build());
                  t.setData("修改成功");
                  t.setIsSuccess(true);
                },
                (e,t)->{
                    t.setMessage("创建失败");
                    t.setIsSuccess(false);
                    t.setCode("201");
                    t.setData(e.getMessage());
                });
    }


    /**
     * 方法描述:查询详情
     * SJC 2018-8-27 16:14:31
     */
    @GetMapping("/notice/showNoticeInfoTiny")
    public String showNoticeInfoTiny(@RequestParam String ntId, Model model) {
        Notice nt = iNoticeService.queryNoticeById(ntId);
        if(!"".equals(nt.getContent())){
            nt.setContent(nt.getContent());
        }
        model.addAttribute("notice", nt);
        //发送的人员
        List<Map<String,Object>> receiver = iNoticeService.queryReceivers(ntId);
        model.addAttribute("receiver", receiver);
        return "base/notice/noticeInfoTinymce";

    }

    /**
     *  方法描述：弹出需要发送公告的人员信息
     *  SJC 2018-8-27 16:14:31
     **/
    @RequestMapping(value = "/notice/showMemberPage",method = RequestMethod.GET)
    public String showAddRoleMemberPage(String noticeId,Model model){
        model.addAttribute("noticeId",noticeId);
        return "base/notice/addNoticeMember";
    }

    /**
     * 方法描述:获取所有用户信息
     * SJC 2018-9-13 19:34:26
     *
     */
    @RequestMapping(value = "/notice/queryUserList",method = RequestMethod.GET )
    @ResponseBody
    public ResultDTO queryUserList(Pageable pageable){
        PageInfo<User> res = roleService.queryUserByUserName(pageable.getPageNumber(),pageable.getPageSize(),"",null,null);
        JSONObject map = new JSONObject();
        map.put("total",res.getTotal());
        map.put("rows",res.getList());
        return  ResultDTO.builder()
                .data(map)
                .build();
    }

    /**
     * 方法描述:插入需要发送人员表
     * SJC 2018-9-13 19:34:02
     *
     */

    @RequestMapping("/notice/addMemberList")
    @ResponseBody
    public ResultDTO addMemberList(@RequestBody ReqTuple reqTuple ,Principal principal){
        String noticeId = reqTuple.getNoticeId();
        List<String> list = reqTuple.getMemberList();
        String uname = principal.getName();
        User user = mysqlUtil.getUserByLoginName(uname);
        return  ResultDTO.builder()
                .data(iNoticeService.insertNoticeSend(noticeId,String.valueOf(user.getId()),list))
                .build();
    }

    /**
     * 方法描述:查询已经发送过的用户，默认打钩
     * SJC 2018-9-13 19:34:26
     *
     */
    @RequestMapping(value = "/notice/querySendMember" )
    @ResponseBody
    public ResultDTO querySendMember(String noticeId,Principal principal)throws Exception{
        User user = mysqlUtil.getUserByLoginName(principal.getName());
        List<String> res = iNoticeService.querySendMember(noticeId,String.valueOf(user.getId()));

        return  ResultDTO.builder()
                .data(res)
                .build();
    }

}